import os
import queue
import re
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime

from moviepy.editor import VideoFileClip

from base import create_movie_v2
from base import oss_client
from service import service_audio
from model.models import db, TSysNovelChapter, TSysFile, \
    TSysTokenUsageHistory, TSysVideo

video_token_price_v1=5000 #每分钟


threadPool = ThreadPoolExecutor(max_workers=16, thread_name_prefix="create_img_")
video_create_q = queue.Queue()
video_create_status = {}

video_temp_folder_path = "../video_temp"
audio_temp_folder_path = "../audio_temp"
type_MP4="mp4"
type_PNG="png"

def create_video_from_images(materials, images_temp_chpater_path ,chapter_id):
    try:
        if not os.path.exists(video_temp_folder_path):
            os.makedirs(video_temp_folder_path)

        output_video_file = str(chapter_id)+"-"+str(time.time()) + ".mp4"
        image_files = []  # 图片文件列表
        text_list = []

        for material in materials:
            image_files.append(material.get("image_path"))
            text_list.append(material.get("subtitle"))

        if len(text_list) == 0:
            return {"success": False, "value": None, "msg": "视频创建异常，字幕创建异常"}

        subtiles = format_subtitle(txt_list=text_list)
        if len(subtiles) == 0:
            return {"success": False, "value": None, "msg": "视频创建异常，字幕创建异常"}

        dest_video_path = video_temp_folder_path+os.sep+output_video_file

        # create_audio_result = service_audio.create_audio_from_text(text=''.join(text_list), chapter_id=chapter_id)
        create_audio_result = service_audio.create_short_audio_from_text(text_list=subtiles, chapter_id=chapter_id)
        #todo:改成短音频

        if create_audio_result is None or create_audio_result == False:
            return {"success": False, "value": None, "msg": "视频创建异常，解说音频未创建成功"}

        mixed_audio_file_path = create_audio_result.get("value").get("mixed_audio_file_path")
        audio_temp_path = create_audio_result.get("value").get("audio_temp_path")
        handled_subtiles = create_audio_result.get("value").get("subtiles")

        create_movie_v2.create_video_from_images(image_files=image_files, subtiles_materials=handled_subtiles, audio_file=mixed_audio_file_path, output_file=dest_video_path)

        chapter = TSysNovelChapter.query.filter_by(id=chapter_id).first()
        if chapter is not None:
            #上传视频
            oss_video_file_name=str(chapter_id)+"-"+str(time.time()) + ".mp4"
            bucket_name="video" + "-" + str(chapter.user_id) + "-" + str(chapter_id)
            oss_client.upload_file(file_path=dest_video_path, file_name=oss_video_file_name, bucket_name=bucket_name)
            tSysFile = TSysFile(
                user_id=chapter.user_id,
                correlation_id=chapter.novel_id,
                correlation_type='novel',
                correlation_sub_id=chapter_id,
                name=chapter.title,
                local_path=oss_video_file_name,
                remote_path=bucket_name,
                file_type=type_MP4,
                create_date=datetime.now(),
                update_date=datetime.now()
            )
            db.session.add(tSysFile)
            db.session.flush()
            file_id = tSysFile.id
            db.session.commit()
            return {"success": True, "value": {"file_id": file_id, "oss_video_file_name": oss_video_file_name,
                                               "video_file_path": dest_video_path,
                                               "mixed_audio_path": mixed_audio_file_path,
                                               "audio_temp_path": audio_temp_path,
                                               "imgs_path": images_temp_chpater_path}, "msg": "视频创建完毕"}
    except Exception as e:
        return {"success": False, "value": None, "msg": "生成视频异常：" + str(e)}



#视频长度
def get_video_duration(file_path):
    if file_path is None:
        return 0

    vedio = VideoFileClip(file_path)
    if vedio is not None:
        vedio_duration = vedio.duration
        vedio.close()
        return vedio_duration
    else:
        return 0


def format_subtitle(txt_list):
    merged_string = ''.join(txt_list)
    merged_string = merged_string.replace("\n", "").replace("\r", "")
    subtitles_list = re.split(r'[。，]', merged_string)
    subtitles_list.pop() #去掉最后的空字符
    return subtitles_list